package com.panfeng.xcloud.im.util;

import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

@Slf4j
@Builder
public class HttpServletRequestUtil {
    public static ServletRequestAttributes getServletRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    public static HttpServletRequest getHttpServletRequest() {
        return getServletRequestAttributes().getRequest();
    }

    public static HttpServletResponse getHttpServletResponse() {
        return getServletRequestAttributes().getResponse();
    }

    public static HttpSession getHttpSession() {
        return getHttpServletRequest().getSession();
    }

    public static void print(String jsonStr){
        HttpServletResponse response = getHttpServletResponse();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        try(
                PrintWriter writer = response.getWriter()
                ){
            writer.print(jsonStr);
        }catch (Exception e){
            e.printStackTrace();
            log.error("输出异常");
        }

    }

}
